<template>
  <div class="codex-app">
    <!-- 活动栏目 -->
    <div class="activebannerMain hidden" v-if="!embed">
      <span class="close hidden"
      @click="handleActivebannerClose()"><i class="el-dialog__close el-icon el-icon-close"></i></span>
      <div class="activebanner"
      @click="handleToActive()">
        <img src="/static/activity/swap-zh-cn.png" alt="" v-if="$store.state.app.language === 'zh-CN'">
        <img src="/static/activity/swap-zh-tw.png" alt="" v-else-if="$store.state.app.language === 'zh-TW'">
        <img src="/static/activity/swap-en.png" alt="" v-else>
      </div>
    </div>
    <div class="content">
      <div class="tab flex">
        <div v-for="(item, index) in menu" :key="index"
          :class="{'active': menuActive === item.value}"
          @click="handleMenu(index)">
          {{ $t(`swap.${item.label}`) }}
        </div>
        <a class="rules" @click="handleJump">
          <!-- 规则 -->
          <span>{{ $t('swap.s10') }}</span>
          <i class="iconfont icon-xinxi iconfont1"></i>
        </a>
      </div>
      <div v-if="menuActive === 0">
        <exchange
        :symbolList="symbolList"
        :tableRowsData="tableRowsData"
        :scatter="scatter"
        :user="user"
        :embed="embed"
        :symbolChecked="symbolChecked"
        :symbolScience="symbolScience"
        @listenCodex="listenCodex"
        @listenWalletLogin="handleWalletLogin"
        @listenWalletPermission="handleWalletPermission" />
      </div>
      <div v-if="menuActive === 1">
        <market
        :symbolList="symbolList"
        :tableRowsData="tableRowsData"
        :scatter="scatter"
        :user="user"
        :embed="embed"
        :symbolChecked="symbolChecked"
        :symbolScience="symbolScience"
        @listenCodex="listenCodex"
        @listenWalletLogin="handleWalletLogin"
        @listenWalletPermission="handleWalletPermission" />
      </div>
      <!-- 记录 -->
      <div class="record">
        <!-- 兑换记录 -->
        <exchange-record  v-if="menuActive === 0" :dataList="dataList" :embed="embed" />
        <market-record  v-if="menuActive === 1" :dataList="dataList" :embed="embed" />
      </div>
      <div class="center tipCls" v-if="menuActive === 0">
        <span>{{$t('swap.s95', {num: swapVolume24H.eosVolume24H})}}</span>
        <span>{{$t('swap.s96', {num: swapVolume24H.count24H})}}</span>
      </div>
      <div class="center tipCls" :style="menuActive === 0 ? 'margin-top: 0;': ''" style="cursor: pointer;">
        <a :href="($store.state.app.language === 'zh-CN' || $store.state.app.language === 'zh-TW') ?
        'https://peckshield.com/zh' : 'https://peckshield.com/en'" target="_blank">
          <span>{{$t('swap.s101')}}</span><!--
          --><span class="colorThis" :style="$store.state.app.language === 'en' ? 'margin-left: 3px' : ''">{{$t('swap.s102')}}</span><!--
          --><span>{{$t('swap.s103')}}</span>
        </a>
      </div>
    </div>
    <!-- 温馨提示 服务暂停-->
    <div v-if="stopSwap">
      <tips :text="$t('swap.s54')"
        :width="400"
        :showBtn = true
        @listenTips="(() => {stopSwap=false})" />
    </div>
    <!-- 温馨提示 扫码登录-->
    <div v-if="walletByPhone">
      <tips :text="$t('bosChain.dontCode')"
        :width="400"
        :showBtn = true
        @listenTips="(() => {walletByPhone=false})" />
    </div>
    <div class="bynewdex" v-if="embed">
      <span style="font-size:16px;vertical-align: middle;">*</span>
      {{$t('swap.s82')}}
    </div>
  </div>
</template>

<script>
import { getTargetOrigin } from '@/utils/validate';
import { bitModel } from '@/utils/eos/bitpeicurrex';
import Tips from '@/components/Tips'; // 弹出提示
import Exchange from './components/Exchange'; // 兑换
import Market from './components/Market'; // 做市商
import MarketRecord from './components/MarketRecord'; // 做市商记录
import ExchangeRecord from './components/ExchangeRecord'; // 兑换记录

export default {
  name: 'Codex',
  data() {
    return {
      user: {}, // 用户信息
      symbolList: [], // 币种、交易对列表
      tableRowsData: {},
      scatter: {},
      symbolScience: 'EOS', // 环境 母币
      menu: [ // 总菜单
        {
          value: 0,
          label: 's1'
        },
        {
          value: 1,
          label: 's2',
        }
      ],
      menuActive: 0, // 0-兑换 1-做市商
      dataList: [], // 订单列表交易对信息
      statusObj: {}, // 服务暂停状态
      stopSwap: false, // 服务暂停
      getOneSymbolTimer: null,
      walletByPhone: false,
      targetOrigin: '',
      bodyScrollHeight: 0,
      symbolChecked: {},
      swapVolume24H: {}, // 兑换24小时成交量和订单数
      timer: null, // 兑换24小时成交量和订单数计时器
      activebanner: true,
    };
  },
  components: {
    Exchange,
    Market,
    ExchangeRecord,
    MarketRecord,
    Tips,
  },
  props: {
    embed: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    '$store.state.app.scatter.identity': {
      handler: function listen() {
        this.scatter = this.$store.state.app.scatter;
      },
      deep: true,
    },
    // 监听账户等级变化
    '$store.state.app.accountInfo': function change(val) {
      this.user = val;
    },
  },
  created() {
    document.title = this.$t(`rout.${this.$route.meta.title}`);
    if (this.getOneSymbolTimer) {
      clearTimeout(this.getOneSymbolTimer)
    }
  },
  mounted() {
    this.handleSwapVolume();
    this.user = this.$store.state.app.accountInfo;
    this.scatter = this.$store.state.app.scatter;
    this.handleMenu(0);
    // 获取订单列表交易对信息
    this.handleGetListData();
    // 服务暂停状态
    this.handleServerStatus();
    if (this.embed) {
      // 如果是内嵌交易
      this.handleEmbedMounted();
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearTimeout(this.timer);
    }
    window.removeEventListener('message', this.handleReceiveMessage, false);
  },
  methods: {
    // 获取兑换币种、交易对
    handleGetCoinSymbel() {
      bitModel.getCodexCoinSymbel({}, (res, tableRowsData) => {
        this.symbolList = res;
        this.tableRowsData = tableRowsData;
      })
    },
    // 获取单个兑换币种、交易对
    handleGetCoinSymbelOne() {
      if (this.getOneSymbolTimer) {
        clearTimeout(this.getOneSymbolTimer)
      }
      const params = {
        way: 'one',
        pairId: this.checkedSymbol.pairId,
      }
      bitModel.getCodexCoinSymbel(params, (res) => {
        const item = res[0];
        const index = this.symbolList.findIndex(v => v.pair_id === item.pair_id);
        if (index !== -1) {
          this.$set(this.symbolList, index, item);
        }
        this.getOneSymbolTimer = setTimeout(() => {
          this.handleGetCoinSymbelOne();
        }, 5000);
      })
    },
    // 总 菜单切换（兑换、做市商）
    handleMenu(val) {
      this.menuActive = val;
      // 获取兑换币种、交易对
      this.handleGetCoinSymbel();
    },
    handleGetListData() {
      this.$http.post('/aiswap/getSwapPairList').then((res) => {
        if (res.code !== 0) {
          this.$message.error(res.msg);
          return;
        }
        const swapPairList = res.swapPairList;
        swapPairList.forEach((v) => {
          const vv = v;
          const symbol1 = vv.pair.split('-')[1];
          const symbol2 = vv.pair.split('-')[2];
          this.$set(vv, 'symbol1', symbol1.toUpperCase());
          this.$set(vv, 'symbol2', symbol2.toUpperCase());
          this.$set(vv, 'symbolFormat', `${symbol1.toUpperCase()}/${symbol2.toUpperCase()}`);
        });
        this.dataList = swapPairList;
      });
    },
    // 监听回传信息
    listenCodex(key, val) {
      if (key === 'getSysbolInfo') {
        this.handleGetCoinSymbel();
      }
      if (key === 'getAccountInfo') {
        this.handleGetAccountInfo()
      }
      if (key === 'getSymbol') {
        this.checkedSymbol = val;
        this.handleGetCoinSymbelOne()
      }
      if (key === 'walletByPhone') {
        this.walletByPhone = true;
      }
      if (key === 'toMarket') {
        this.symbolChecked = val || {};
        this.handleMenu(1);
      }
    },
    // 账户登录命令传递
    handleWalletLogin() {
      if (this.embed) {
        const params = {
          action: 'walletLogin',
          data: null,
        }
        window.parent.postMessage(JSON.stringify(params), this.targetOrigin);
        return;
      }
      this.$emit('listenWalletLogin', true);
    },
    /**
     * 钱包授权
     */
    handleWalletPermission() {
      if (this.embed) {
        const params = {
          action: 'walletLogin',
          data: null,
        }
        window.parent.postMessage(JSON.stringify(params), this.targetOrigin);
        return;
      }
      const checkWallet = localStorage.getItem('checkWallet');
      if (checkWallet && !Number(checkWallet)) {
        this.$emit('listenWalletPermission', true);
        return;
      }
      this.$emit('listenWalletLogin', true);
    },

    // 获取账号会员信息
    handleGetAccountInfo() {
      const scatter = this.scatter;
      if (scatter && scatter.identity) {
        const params = {
          account: scatter.identity.accounts[0].name
        }
        this.$http.post('/account/getAccountInfo', params).then((res) => {
          if (res.code === 1007) {
            const info = {
              account: this.scatter.identity.accounts[0].name,
              chain: this.chain,
              ambassadorType: null,
              anonymous: 0,
              consumeLevel: 0,
              discountRate: 1,
              email: null,
              expireTime: null,
              isDealRemind: 0,
              isMarketRemind: 0,
              isRenew: 0,
              joinTime: null,
              language: this.$store.state.app.language,
              level: 0,
              maxLevel: 10,
              ndxStaked: 0,
              noRemindPartial: 0,
              orderTime: null,
              remainDealRemindCount: 10,
              remainDrawCount: 0,
              remainMarketRemindCount: 5,
              renewDuration: null,
              stakeLevel: 0,
              totalSaveAmount: 0,
              usedMarketRemindCount: 0,
              vipImageUrl: null,
              vipMode: 0,
              weight: 0,
              weightRatio: 0,
              remainFreeOrderCount: 1
            }
            this.$store.dispatch('setAccountInfo', info);
          }
          if (res.code !== 0) {
            return;
          }
          if (res.code === 0) {
            this.$store.dispatch('setAccountInfo', res.accountInfo || {});
          }
        });
        return;
      }
      this.$store.dispatch('setAccountInfo', {});
    },
    handleServerStatus() {
      bitModel.swapServerStartus({}, (res) => {
        if (res && res.rows && res.rows.length > 0) {
          this.statusObj = {
            status: res.rows[0].value
          }
          if (Number(this.statusObj.status) === 0) {
            this.stopSwap = true;
          }
        }
      })
    },
    // 衰减公告跳转链接
    handleJump() {
      const url = {
        'zh-CN': 'https://newdex.zendesk.com/hc/zh-cn/articles/360041372572-Newdex-%E9%97%AA%E5%85%91-%E8%A7%84%E5%88%99',
        'zh-TW': 'https://newdex.zendesk.com/hc/zh-tw/articles/360041372572-Newdex-%E9%96%83%E5%85%8C-%E8%A6%8F%E5%89%87',
        en: 'https://newdex.zendesk.com/hc/en-us/articles/360041372572--Newdex-Swap-Rules',
        ko: 'https://newdex.zendesk.com/hc/ko/articles/360041372572--Newdex-Swap-Rules',
      }
      window.open(url[this.$store.state.app.language]);
    },
    // 嵌入交易代码 begin
    handleEmbedMounted() {
      this.targetOrigin = getTargetOrigin();
      // 获取配置
      console.log('newdexSwap -> request getConfig'); // eslint-disable-line
      const messageGetConfig = { action: 'getConfig', data: null }
      window.parent.postMessage(JSON.stringify(messageGetConfig), this.targetOrigin);
      // 获取用户
      console.log('newdexSwap -> request getAccount'); // eslint-disable-line
      const messageGetAccount = { action: 'getAccount', data: null }
      window.parent.postMessage(JSON.stringify(messageGetAccount), this.targetOrigin);
      this.$nextTick(() => {
        // 回调监听
        window.addEventListener('message', this.handleReceiveMessage, false);
        this.handleGetBodyScrollHeight();
      })
    },

    // 嵌入交易代码 addEventListener message callback
    handleReceiveMessage(event) {
      // 这里不准确，chrome没有这个属性
      const origin = event.origin || event.originalEvent.origin;
      if (origin === window.location.origin) return;
      console.log('newdexSwap -> get back event'); // eslint-disable-line
      console.log(event.data); // eslint-disable-line
      const message = JSON.parse(event.data);
      // Bus.$emit('busReceiveMessage', message.action, message.data);
      switch (message.action) {
        case 'getConfig': {
          const params = message.data;
          const sapp = this.$store.state.app;
          if (params.language && params.language !== sapp.language) {
            this.$i18n.locale = params.language;
            this.$store.dispatch('setLanguage', params.language);
          }
          if (params.theme && params.theme !== sapp.theme) {
            const theme = params.theme === 'white' ? 'theme-278EDA' : 'theme-1B1D27';
            this.$store.dispatch('setTheme', theme);
          }
          if (params.node && params.node.eos.host !== sapp.nodeChecked.eos.host) {
            this.$store.dispatch('setNodeChecked', params.node); // 默认节点配置
          }
          break;
        }
        case 'getAccount': {
          const params = message.data;
          localStorage.setItem('Frontend-Token', params.token);
          // 账户名不同
          this.$store.dispatch('setScatter', params);
          break;
        }
        case 'getArbitrarySignature': {
          break;
        }
        default:
      }
    },
    // 嵌入交易 body 高度实时获取
    handleGetBodyScrollHeight() {
      this.$nextTick(() => {
        setTimeout(() => {
          const tag = window.document.getElementById('appLayout');
          const scrollHeight = tag ? tag.scrollHeight : 0;
          if (this.bodyScrollHeight !== scrollHeight) {
            this.bodyScrollHeight = scrollHeight;
            console.log('newdexSwap -> request setHeight'); // eslint-disable-line
            const messageGetConfig = { action: 'setHeight', data: { height: scrollHeight } }
            console.log(messageGetConfig); // eslint-disable-line
            window.parent.postMessage(JSON.stringify(messageGetConfig), this.targetOrigin);
          }
          this.handleGetBodyScrollHeight();
        }, 800)
      });
    },
    // 获取兑换成交量订单数
    handleSwapVolume() {
      this.$http.get('/aiswap/getSwapVolume24H').then((res) => {
        if (res.code !== 0) {
          this.$message.error(res.msg);
          return;
        }
        this.swapVolume24H = JSON.parse(res.swapVolume24H);
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          this.handleSwapVolume();
        }, 60000);
      });
    },
    // 活动
    handleActivebannerClose() {
      this.activebanner = !this.activebanner;
    },
    handleToActive() {
      // if (this.embed) {
      //   const messageGetAccount = { action: 'getAccount', data: null }
      //   window.parent.postMessage(JSON.stringify(messageGetAccount), this.targetOrigin);
      //   return;
      // }
      this.$router.push('/events/ndx-swap-trading-contest');
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/variables.scss";

.codex-app {
  max-width: 1260px;
  margin: 0 auto;
  padding: 10px 0 30px 0;
  position: relative;

  .bynewdex {
    position: relative;
    padding: 20px 0;
    width: 100%;
    text-align: right;
    font-size: 12px;
    color: #999;
  }

  .content {
    padding-top: 10px;

    .tab {
      position: relative;
      border-bottom: 1px solid #D7D7D7;
      background: #fff;

      div {
        cursor: pointer;
        padding: 10px 30px;
        border-bottom: 1px solid transparent;
        margin-bottom: -1px;
      }

      .active {
        color: #278EDA !important;
        border-bottom: 1px solid #278EDA;
      }

      .rules {
        position: absolute;
        right: 10px;
        top: 10px;
      }

    }
  }

  .record {
  }

  .tipCls {
    font-size: 12px;
    color: #999;
    margin-top: 20px;
    height: 17px;
    span {
      display: inline-block;
    }

    a:hover {
      color: #999 !important;
    }
  }
}

.activebannerMain {
  position: relative;

  span.close {
    position: absolute;
    top: 0;
    right: 0;
    padding: 0 3px;
    background: rgba(255, 255, 255, .7);
    cursor: pointer;

    i {
      font-size: 20px;
    }
  }
  .activebanner {
    display: flex;
    justify-items: center;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
    width: 100%;
    height: 60px;
    color: #fff;
    overflow: hidden;
    cursor: pointer;
    img {
      width: 100%;
    }
    span:nth-child(1) {
      font-size: 20px;
      padding-right: 15px;
    }
    span:nth-child(2) {
    }
    span:nth-child(3) {
      display: inline-block;
      padding: 3px 30px;
      border-radius: 5px;
      color: #B15132;
      background: #FFFB75;
      margin-left: 100px;
      cursor: pointer;
    }
  }
}

.theme-1B1D27 {
  .tab {
    background: $-black2 !important;
    border-color: $-black1 !important;

    div {
      border-color: $-black1 !important;
    }

    .active {
      border-color: #278EDA !important;
    }
  }
}
</style>
